package javaTree.tree.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javaTree.tree.dao.MenuDao;
import javaTree.tree.entity.Menu;

@Controller
public class menuController {

    @Autowired
    private MenuDao menuDao;

    @RequestMapping("/show.do")
    public String show() {
        return "show";
    }


    @RequestMapping("/menu.do")
    @ResponseBody
    public ResultRespone<Map<String, Object>> findTree() {
        ResultRespone<Map<String, Object>> rr;
        Map<String, Object> data = new HashMap<String, Object>();
        //找到所有的菜单
        List<Menu> allMenu = menuDao.findTree();
        //跟菜单的存放集合
        List<Menu> rootMenu = new ArrayList<Menu>();
        for (Menu nav : allMenu) {
            if (nav.getParentId() == null) {
                rootMenu.add(nav);
            }
        }

        for (Menu nav : rootMenu) {
            List<Menu> listChild = getChild(nav.getId(), allMenu);
            nav.setChildren(listChild);

        }
        data.put("menu", rootMenu);
        rr = new ResultRespone<Map<String, Object>>(1, "获取菜单");
        rr.setData(data);
        return rr;

    }

    public List<Menu> getChild(String id, List<Menu> allMenu) {
        //存放子菜单的集合
        List<Menu> listChild = new ArrayList<Menu>();
        for (Menu nav : allMenu) {//遍历所有的菜单的parentid
            if (nav.getParentId() != null){
                if (nav.getParentId().equals(id)) {
                    listChild.add(nav);
                }
            }
        }
        if (listChild.size() == 0) {
            return null;
        }
        //递归
        for (Menu nav : listChild) {
            nav.setChildren(getChild(nav.getId(), allMenu));
        }
        return listChild;
    }
}
